import { defineStore } from "pinia";
import { api, API_PREFIX, API_TSL_FRONTEND } from "boot/axios";
import { useWOReviewStore } from "./woReviewStore";
import { useWoRoutingStore } from "./woroutinghistStore";
// import { useUserStore } from './userStore'
import { Loading } from "quasar";

export const useWoDetailsStore = defineStore("wodetails", {
  state: () => ({
    orderNo: null,
    allowAction: false,
    wod: [], // original data

    // Top: Status Bar
    statusInfo: [],

    // Tab 1: Order Info
    orderInfo: [],

    // Tab 2: Design Info
    desingInfo: [],

    // Tab 3: Product Info
    prodInfo: [],
    currProdRemark: [],
    new_productionRemark:[],

    // Tab 4: Article Info
    articleInfo: [],
    routingHistory: [],

    colorImgs: [],
    stoneImgs: [],
    // Others:
    article: [],

    // Worker
    workTimer: [],

    // QC, Leader, Stone Check
    workOrderReview: [],

    qcFR: [], // qcFR = all fail reason choices (provided by db) // pk, reason, unit

    // Dispatcher
    routing: [],
    routingTableOptions: [],

    displayConfig:{}
  }),

  getters: {
    getOrderNo: (state) => {
      return state.orderNo;
    },

    getWorkTimer: (state) => {
      // return state.workTimer[0]
      return state.workTimer.length ? state.workTimer[0] : [];
    },
  },

  actions: {
    //roleName

    async getWODetails(orderNo, accID, role) {
      Loading.show();
      console.log("------>role: ", role);
      this.allowAction = false;
      this.wod = [];
      this.workTimer = [];
      this.workOrderReview = [];
      this.currProdRemark = [];
      this.colorImgs = []
      this.stoneImgs = []

      const useWOReview = useWOReviewStore();
      const useWoRouting = useWoRoutingStore();
      useWoRouting.order_no = orderNo;

      try {
        const res = await api.get(
          API_TSL_FRONTEND + "/OrderView/" + `${orderNo}/`,
          { params: { account_pk: accID } }
        );

        this.orderNo = orderNo;

        const status = res.status;

        const data = res.data.data;
        console.log("getWODetails data:", data);
        this.colorImgs = res.data.data.colorImgs ==null ? [] : res.data.data.colorImgs
        this.stoneImgs = res.data.data.stoneImgs ==null ? [] : res.data.data.stoneImgs
        console.log("stoneImgs: ", this.stoneImgs);
        console.log("colorImgs: ", this.colorImgs);
        // set values
        this.statusInfo = data.status;
        console.log("statusInfo: ", this.statusInfo);

        this.displayConfig = data.display_config == undefined ? {} : data.display_config
        console.log("displayConfig: ", this.displayConfig);

        this.orderInfo = data.order;
        console.log("orderInfo: ", this.orderInfo);

        this.desingInfo = data.design;
        console.log("designInfo: ", this.desingInfo);

        this.prodInfo = data.prod;
        console.log("prodInfo: ", this.prodInfo);
        console.log('prod_remark_list', data.prod_remark_list);
        const new_productionRemark = data.prod_remark_list
        this.new_productionRemark = new_productionRemark
        const productionRemark = this.prodInfo.prodRemark
          ? this.prodInfo.prodRemark
          : []; // all the prod_remark_list
        console.log("prodRemark: ", productionRemark);

        if (productionRemark.length > 0) {
          productionRemark.forEach((pr) => {
            const prodRemark = {
              pk: pr.pk,
              config_pk: pr.config_pk,
              ans: pr.ans,
              remark: pr.remark.split(/<NUM>/),
              type: pr.type,
              isChosen: pr.ans > 0 ? true : false,
              prev_ans: pr.ans,
              // prev_isChosen: (pr.ans > 0) ? true : false
            };
            this.currProdRemark.push(prodRemark);
          });
        }
        // console.log("currProdRemark: ", this.currProdRemark);

        this.articleInfo = data.article;
        // console.log("articleInfo: ", this.articleInfo);

        // routingHistory
        let rh = this.articleInfo.routingHistory
          ? this.articleInfo.routingHistory
          : [];
        this.routingHistory = [];
        console.log("----------------rh: ", rh);
        if (rh.length > 0) {
          rh.forEach((rhitem) => {
            let item = null;
            // console.log("--------------rhitem: ", rhitem);
            if (rhitem.length > 0) {
              item = rhitem[rhitem.length - 1]; // take the latest record
              this.routingHistory.push(item);
            }
          });
        }
        console.log("routingHistory: ", this.routingHistory);

        this.qcFR = data.fail_reason_list;

        const record = data.record;
        console.log("record: ", record);

        // WORKER
        if (Object.keys(record).length > 0) {
          if (role === "WORKER") {
            let currStatus =
              record.worker.actionRecord.length > 0
                ? record.worker.actionRecord[
                    record.worker.actionRecord.length - 1
                  ]
                : null;
            let act = null;
            let wtTime = null;
            if (currStatus) {
              act = currStatus.action.toLowerCase();
              wtTime = currStatus.time ? currStatus.time : "";
            } else {
              act = "init";
              wtTime = "";
            }
            console.log('currStatus', act);

            let wt = {
              currentStatus: act,
              flow: data.status.flow,
              action: act,
              time: wtTime,
            };
            this.workTimer.push(wt);
            if (data.editable) {
              this.allowAction = true;
            }
            // }
          } else if (
            role === "QC" ||
            role === "Teamleader" ||
            role === "StoneQC"
          ) {
            let currStatus =
              role === "QC"
                ? record.qcCheck
                : role === "Teamleader"
                ? record.leaderCheck
                : record.stoneCheck;
            let act = currStatus.check_time
              ? "complete"
              : currStatus.rec_time
              ? "start"
              : null;
            let fail_detail = currStatus.fail_detail;
            let fail_detail_len_not_zero = fail_detail.length > 0;
            const selectedFailReason = [];
            this.qcFR.forEach((fr) => {
              let chosen = false;
              let qty = 1;
              if (fail_detail_len_not_zero) {
                let find_result = fail_detail.find(
                  (fd) => fd.fail_reason_id === fr.pk
                );
                chosen = find_result ? true : false;
                qty = find_result ? find_result.fail_qty : 1;
              }

              let tp = {
                id: fr.pk,
                reason: fr.reason,
                unit: fr.unit,
                qty: qty,
                isChosen: chosen,
              };
              selectedFailReason.push(tp);
            });

            let wor = {
              currentStatus: act,
              flow: data.status.flow,
              result:
                currStatus.failed === true
                  ? "fail"
                  : currStatus.failed === false
                  ? "pass"
                  : "",
              editable: data.editable,
              allow_reset: currStatus.allow_reset,
              remark: currStatus.remark,
              selectedFailReason: selectedFailReason,
              checkTime: currStatus.check_time, // 工序状态 will show the latest complete time
              checklist_id: currStatus.check_record_obj_pk,
              failReason: this.qcFR,
            };
            this.workOrderReview.push(wor);
            console.log("workOrderReview: ", this.workOrderReview);
            this.allowAction = data.editable;
            useWOReview.setWOReview();
          } else if (role === "CenterSender") {
            // do something
          } else {
            console.log("cannot get role current status info");
          }
        }
        if (role === "CenterSender") {
          this.routing = this.articleInfo.routing;
          this.routingTableOptions = data.routing_table.options;
          useWoRouting.setParams(this.routing, this.routingTableOptions, this.orderNo);
        }
        Loading.hide();
        return true;
      } catch (error) {
        Loading.hide();
        return false;
      }
    },

    setWorkOrderDetails(orderNo) {
      this.orderNo = orderNo;
      console.log("orderNo: ", this.orderNo);
    },

    async updateProdRemark(prodRemarks) {
      let prodRemark = [];
      prodRemarks.forEach((pr) => {
        let pr_temp = {
          config_pk: pr.pk,
          ans: pr.ans,
        };
        prodRemark.push(pr_temp);
      });

      const params = {
        prodRemark: prodRemark,
      };

      console.log("params: ", params);

      try {
        Loading.show();
        const res = await api.post(
          API_TSL_FRONTEND +
            "/OrderView/" +
            `${this.orderNo}` +
            "/update_production_remark/",
          params
        );
        console.log("update production remark result: ", res);
        Loading.hide();
        return true;
      } catch (error) {
        // console.log(res.error)
        Loading.hide();
        return false;
      }
    },

    async getActualBom(){
      try {
        Loading.show();

        const res = await api.get(
          API_TSL_FRONTEND +
            "/OrderView/" +
            `${this.orderNo}` +
            "/get_actual_bom/"
            /* ,
          params */
        );
        console.log("getActualBom: ", res);
        Loading.hide();

        return res
      } catch (error) {
        Loading.hide();
        return false;
      }
     
    }
  },
});
